package com.mall507.fivepeaks.activity.find;

import android.os.Build;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.hzh.frame.comn.annotation.ViewInject;
import com.hzh.frame.comn.callback.HttpCallBack;
import com.hzh.frame.core.HttpFrame.BaseHttp;
import com.hzh.frame.ui.activity.AbsRecyclerViewUI;
import com.hzh.frame.util.AndroidUtil;
import com.hzh.frame.widget.rxbus.MsgEvent;
import com.hzh.frame.widget.rxbus.RxBus;
import com.hzh.frame.widget.xrecyclerview.RecyclerViewHolder;
import com.mall507.comn.model.LostFound;
import com.mall507.comn.model.Message;
import com.mall507.comn.tools.UserTools;
import com.mall507.fivepeaks.R;
import com.mall507.fivepeaks.activity.community.CommunityArtRFM;
import com.mall507.fivepeaks.activity.main.MainOriginalRFM;
import com.mall507.fivepeaks.util.Util;
import com.mall507.fivepeaks.widget.Banner.BGABanner;
import com.mall507.fivepeaks.widget.imageview.CircleImageView;
import com.mall507.fivepeaks.widget.imageview.ExpandImageView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 详情
 * @date 2019/8/8
 */
@Route(path = "/find/FindLostFoundInfoRUI")
public class FindLostFoundInfoRUI extends AbsRecyclerViewUI<Message> {

    @ViewInject(R.id.collection) //收藏
    LinearLayout collection;
    @ViewInject(R.id.img_collection) //收藏图片
    ImageView img_collection;
    @ViewInject(R.id.lickNumber)
    TextView lickNumber;
    @ViewInject(R.id.send) //发送评论
    TextView send;
    @ViewInject(R.id.comment) //评论内容
    EditText comment;
    

    private int page = 0;

    View headView;
    String views="";
    String comments="";
    String collections="";

    @Override
    protected int setLayoutId() {
        return R.layout.ui_rv_comn_goods_item_info;
    }

    @Override
    protected void bindView() {
        getTitleView().setContent("详情");
        collection.setVisibility(View.GONE);
        lickNumber.setText(getIntent().getStringExtra("collection_count"));
        String str = getIntent().getStringExtra("picsize");
        if (Integer.parseInt(str) > 0){
            headView = getLayoutInflater().inflate(R.layout.head_rv_comn_goods_item_info, null);
            getAdapter().setHeaderView(headView);
        }else {
            headView = getLayoutInflater().inflate(R.layout.head_rv_comn_goods_item_info2, null);
            getAdapter().setHeaderView(headView);
        }
        getHeadData();
        isCollection();
        collection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final int collection_count = Integer.parseInt(lickNumber.getText().toString());
                if (UserTools.getInstance().getIsLogin()){
                    if (page == 0){
                        img_collection.setImageDrawable(getResources().getDrawable(R.mipmap.like_blue));
                        lickNumber.setText(String.valueOf(collection_count+ 1));
                        setCollection();
                        page = 1;
                    }else if (page == 1){
                        img_collection.setImageDrawable(getResources().getDrawable(R.mipmap.like_hui));
                        lickNumber.setText(String.valueOf(collection_count+ -1));
                        cancelCollection();
                        page = 0;
                    }
                }else {
                    alert("请登录之后尝试");
                    ARouter.getInstance().build("/login/login").navigation();
                }
            }
        });

        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (UserTools.getInstance().getIsLogin()){
                    if (TextUtils.isEmpty(comment.getText())){
                        alert("评论不能为空");
                    }else {
                        sendComment();
                    }
                }else {
                    alert("请登录之后尝试");
                    ARouter.getInstance().build("/login/login").navigation();
                }
            }
        });
    }

    @Override
    protected String setHttpPath() {
        return getIntent().getStringExtra("commentRequestPath");
    }

    @Override
    protected JSONObject setHttpParams() {
        JSONObject params = new JSONObject();
        try {
            params.put("id", getIntent().getStringExtra("id"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return params;
    }

    @Override
    protected List<Message> handleHttpData(JSONObject response) {
        List<Message> list = new ArrayList<>();
        if (200 == response.optInt("code")) {
            JSONArray jsonArray = response.optJSONArray("data");
            if (jsonArray != null && jsonArray.length() > 0) {
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject object = jsonArray.optJSONObject(i);
                    JSONObject member = jsonArray.optJSONObject(i).optJSONObject("member");
                    Message model = new Message();
                    model.setNid(object.optString("id"));
                    if (member != null && member.length()>0){
                        model.setHead(member.optString("head_img"));
                        model.setName(member.optString("nickname"));
                    }
                    model.setDesc(object.optString("content"));
                    model.setTime(object.optString("create_at"));
                    list.add(model);
                }
            }
        }
        return list;
    }

    private void getHeadData() {
        JSONObject params = new JSONObject();
        try {
            params.put("id", getIntent().getStringExtra("id"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        BaseHttp.getInstance().query(getIntent().getStringExtra("headRequestPath"), params, new HttpCallBack() {
            @Override
            public void onSuccess(JSONObject response) {
                if(200==response.optInt("code")){
                    final JSONObject data = response.optJSONObject("data");
                    JSONObject params = new JSONObject();
                    try {
                        params.put("type", getIntent().getStringExtra("type"));
                        params.put("id", getIntent().getStringExtra("id"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    BaseHttp.getInstance().query("Action/viewBlog", params, new HttpCallBack() {
                        @Override
                        public void onSuccess(JSONObject response) {
                            int view = data.optInt("clicks") + 1;
                            views = String.valueOf(view);
                            comments = data.optString("comment_count");
                            collections = data.optString("collection_count");
                            setEvent(collections,comments,views);
                            ((TextView) headView.findViewById(R.id.head_pageview)).setText(view + "人浏览"); //浏览数
                            super.onSuccess(response);
                        }
                    });
                    
                    if(data!=null){
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                            headView.setText(R.id.content, String.valueOf(Html.fromHtml(model.getContent(),Html.FROM_HTML_MODE_COMPACT)));
                            ((TextView)headView.findViewById(R.id.head_content)).setText(Html.fromHtml(data.optString("desc"),Html.FROM_HTML_MODE_COMPACT)); //文章内容
                        }else {
                            ((TextView)headView.findViewById(R.id.head_content)).setText(Html.fromHtml(data.optString("desc"))); //文章内容

                            //                            holder.setText(R.id.content, String.valueOf(Html.fromHtml(model.getContent())));
                        }
                        ((TextView)headView.findViewById(R.id.head_title)).setText(data.optString("title")); //文章标题
//                        ((TextView)headView.findViewById(R.id.head_content)).setText(data.optString("desc")); //文章内容
                        ((TextView)headView.findViewById(R.id.head_time)).setText(data.optString("ctime")); //文章发布时间
                        lickNumber.setText(data.optString("collection_count")); //文章收藏数量
                        JSONArray pics=data.optJSONArray("imgs");
                        if (pics.length()>0){
                            List<String> listUrl=new ArrayList<>();
                            for(int i=0;i<pics.length();i++){
                                listUrl.add(pics.optString(i));
                            }
                            bindTopBannerData(listUrl);
                        }
                    }
                }
            }
        });
    }

    /**
     * 绑定banner数据
     */
    private void bindTopBannerData(List<String> listUrl) {
        BGABanner banner = headView.findViewById(R.id.head_banner);
            banner.setAdapter(new BGABanner.Adapter<View, String>() {
                @Override
                public void fillBannerItem(BGABanner banner, View itemView, String url, int position) {
                    SimpleDraweeView simpleDraweeView = itemView.findViewById(R.id.sdv_item_fresco_content);
                    simpleDraweeView.setImageURI(url);
                }
            });
            banner.setData(R.layout.homerecycle_top_banner_content, listUrl, null);
    }

    @Override
    protected int setItemLayoutId(int viewType) {
        return R.layout.item_rv_comn_goods_item_info;
    }

    @Override
    protected void bindItemData(RecyclerViewHolder holder, int position, Message model) {
        holder.setText(R.id.name, model.getName());
        holder.setText(R.id.desc, model.getDesc());
        holder.setText(R.id.time, model.getTime());
        ((CircleImageView) holder.getView(R.id.icon)).setImageURI(model.getHead());
    }

    private void isCollection(){
        BaseHttp.getInstance().query("Action/isCollection", getParams(), new HttpCallBack() {
            @Override
            public void onSuccess(JSONObject response) {
                if (response.optInt("data") == 1){
                    page = 1;
                    img_collection.setImageDrawable(getResources().getDrawable(R.mipmap.like_blue));
                }else {
                    page = 0;
                    img_collection.setImageDrawable(getResources().getDrawable(R.mipmap.like_hui));
                }
                super.onSuccess(response);
            }
        });
    }

    private void setCollection(){
        BaseHttp.getInstance().query("Action/collection", getParams(), new HttpCallBack() {
            @Override
            public void onSuccess(JSONObject response) {
                JSONObject data = response.optJSONObject("data");
                collections = data.optString("collection_count");
                setEvent(data.optString("collection_count"),comments,views);
                super.onSuccess(response);
            }
        });
    }

    private void cancelCollection(){
        BaseHttp.getInstance().query("Action/cancelCollection", getParams(), new HttpCallBack() {
            @Override
            public void onSuccess(JSONObject response) {
                JSONObject data = response.optJSONObject("data");
                collections = data.optString("collection_count");
                setEvent(data.optString("collection_count"),comments,views);
                super.onSuccess(response);
            }
        });
    }

    private JSONObject getParams() {
        JSONObject params = new JSONObject();
        try {
            params.put("type", getIntent().getStringExtra("type"));
            params.put("id", getIntent().getStringExtra("id"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return params;
    }

    private void sendComment(){
        JSONObject params = new JSONObject();
        try {
            params.put("type", getIntent().getStringExtra("type"));
            params.put("id", getIntent().getStringExtra("id"));
            params.put("content", comment.getText().toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        BaseHttp.getInstance().query("comment/subProductComment", params, new HttpCallBack() {
            @Override
            public void onSuccess(JSONObject response) {
                if (200 == response.optInt("code")){
                    onRefresh();
                    alert(response.optString("msg"));
                    JSONObject data = response.optJSONObject("data");
                    comments = data.optString("comment_count");
                    setEvent(collections,comments,views);
                    comment.getText().clear();
                }else {
                    alert(response.optString("msg"));
                }
                super.onSuccess(response);
            }
        });
    }

    private void setEvent(String collection,String comment,String views){
        HashMap<String,Object> map = new HashMap<>();
        map.put("position",getIntent().getStringExtra("position"));
        map.put("collection",collection);
        map.put("views",views);
        map.put("comment",comment);
        MsgEvent msgEvent=new MsgEvent(FindLostFoundRFM.TAG,new Gson().toJson(map));
        RxBus.getInstance().post(msgEvent);
    }
    
}
